<template>
	<div class="index-con"
    v-longpress="handleLongPress"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
    @click="isMoreOpen=false">
    <div style="display:none">{{dtitle}}</div>
    <div :class="isRecording ? '' : 'modal-display'" class="record-modal">
      <div class="wrapper">
        <div class="modal-loading"></div>
      </div>
      <div class="modal-title">
        {{title}}
      </div>
    </div>
    <div class="group-menber" v-if="currentConversation.type === 'GROUP'">
      <div class="top-text">
        <span>工作人员在线时间：9:00-19:00</span>
        <img src="@/assets/image/tuanduijieshao@2x.png" @click="fngoMempage" />
      </div>
      <div class="mem-list">
        <div class="right-mem">
          <ul>
            <template v-for="(item,index) in converMember">
              <li :key="index" v-if="item.allowPrivateChat">
                <div @click="fnchangeConver(item.imAccount)">
                  <avatar :src="item.faceUrl" :imgType="2">
                    <img src="../assets/image/ic_message_fill@2x.png" class="icon-pri-chat" />
                  </avatar>
                </div>
                <p>{{item.healthManagerTypeName}}</p>
                <h5>{{item.nickname}}</h5>
                <!-- <div class="zan-div"></div> -->
              </li>
            </template>
          </ul>
        </div>
        <div class="center-line" v-if="currentMemJudge"></div>
        <div class="left-mem">
          <ul>
            <template v-for="(item,index) in converMember">
              <li :key="index" v-if="!item.allowPrivateChat">
                <avatar :src="item.faceUrl" />
                <p>{{item.healthManagerTypeName}}</p>
                <h5>{{item.nickname}}</h5>
                <!-- <div class="zan-div active"></div> -->
              </li>
            </template>
          </ul>
        </div>
      </div>
    </div>
    <!-- {{currentMessageList}} -->
    <div class="chat-con" ref="message-list" @scroll="onScroll">
      <!-- <div class="no-more" v-if="!(!isCompleted||!isCompletedService)">没有更多了</div> -->
      <template v-for="(message,index) in currentMessageList02">
        <!-- <div class="top-time" :key="index" v-if="topTimeList[index]&&topTimeList[index].time">{{ topTimeList[index].time | fildate}}</div> -->
        <message-item :key="message.ID" :message="message" @fnaiteItem="fnaiteItem" :imageArr="imageArr" />
      </template>
    </div>
    <div class="send-box" v-if="currentConversation.type === 'C2C'||currentConversation.type === 'GROUP' || $route.query.status == 2" @click.stop>
      <div class="bottom-div" v-if="prestatus">
        <!-- <div class="btn-left" @click="chooseRecord">
          <img src="@/assets/image/ic_yuyin@3x.png" v-if="!isRecord" />
          <img src="@/assets/image/ic_jianpan@3x.png" v-else />
        </div> -->
        <div v-if="!isRecord" class="input-div">
          <input type="text" class="input" id="msgInput" ref="msgInput" v-model.lazy:value="messageContent" confirm-type="send" 
          @focus="fninfocus($event)" @blur="fninblur()" @input="inputChange" @keyup.enter='sendMessage' />
        </div>
        <div class="record" id="record" v-else-if="isRecord">
          <template v-if="!isRecording">
            按住 说话
          </template>
          <template v-if="isRecording">
            抬起 停止
          </template>
        </div>
        <div class="btn-right" @click="sendMessage" v-if="messageContent.length !== 0&&prestatus">发送</div>
        <div class="btn-right" @click="handleMore()" v-else>
          <img src="@/assets/image/ic_tianjia@3x.png" />
        </div>
      </div>
      <div class="bottom-div not-send" v-else>
        <!-- <div class="btn-left">
          <img src="@/assets/image/ic_jianpan@3x.png" />
        </div> -->
        <div class="not-send-text">您的服务已到期</div>
        <div class="btn-right">
          <img src="@/assets/image/ic_tianjia@3x.png" />
        </div>
      </div>
<!--    更多部分-->
      <div class="bottom-image" v-if="isMoreOpen">
        <div class="block" @click="sendPhoto('album')">
          <img src="@/assets/image/ic_xiangce@3x.png" />
          <p> 图片</p>
        </div>
        <div class="block" @click="sendPhoto('camera')">
          <img src="@/assets/image/ic_paishe@3x.png" />
          <p>拍摄</p>
        </div>
      </div>
      <div class="quote-txt" v-if="quoteFlag && quotetxt">{{quotetxt}}
        <img src="@/assets/image/bg_modal_close.png" class="quote-close" @click="quoteCloseFn" alt="">
      </div>
    </div>
   
    <!-- <image-previewer /> -->
	</div>
</template>
<script>
import { mapState , mapGetters } from 'vuex'
import { getFullDate } from '../utils/date'
import { apiGetmoreC2cMessage , apiGetmoreGroupMessage , getbaseTime , apithirdmjknotify , apiJsSdkSign, apiGetHmInfo } from '@/api/im/api'
import MessageItem from '@/components/pages/message-item'
// import ImagePreviewer from '@/components/pages/image-previewer'
import wx from 'weixin-js-sdk'
// const audioContext = wx.createInnerAudioContext()
// const recorderManager = wx.getRecorderManager()
// const recordOptions = {
//   duration: 60000,
//   sampleRate: 44100,
//   numberOfChannels: 1,
//   encodeBitRate: 192000,
//   format: 'aac' // 音频格式，选择此格式创建的音频消息，可以在即时通信 IM 全平台（Android、iOS、微信小程序和Web）互通
// }
var starttime = 0;
var endtime = 0;
var scrolltopnum = 0;

var reqCount = 0;
export default {
  title: '米洛健康',
  data() {
    return {
      quoteFlag: false,
      quotetxt:'',
      hmname: '',
      isCompletedService: false,
      topTimeList: [],
      moreListJudge: false,
      safeBottom: 34, // iphoneX底部home高度
      isRecord: false,
      isRecording: false,
      isMoreOpen: false,
      isFocus: false,
      messageContent: '', //输入内容
      canSend: false,
      startPoint: 0,
      title: '正在录音',
      listType: 'groupAt', // 标示1v1通话和群通话,艾特用户
      oldLength: 0,
      mmorejudge: false,
      statusType: 0, //服务状态 2结束
      convListArr:[]
    }
  },
  components:{
    MessageItem,
    // ImagePreviewer
  },
  computed: {
    ...mapState({
      isSDKReady: state => state.user.isSDKReady,
      currentConversation: state => state.conversation.currentConversation,
      currentMessageList: state => state.conversation.currentMessageList,
      isCompleted: state => state.conversation.isCompleted,
      currentMemberList: state => state.group.currentMemberList,
      converMember: state => state.conversation.converMember,
      userID: state => state.user.userID,
      selectedMember: state => state.conversation.selectedMember,
      currentUserProfile: state => state.user.currentUserProfile,
      converList02: state => state.conversation.converList02
    }),
    ...mapGetters(['toAccount', 'hidden', 'currentConversationType', 'isIphoneX']),
    prestatus(){//开通状态
      if(this.converList02[this.currentConversation.conversationID]&&this.converList02[this.currentConversation.conversationID].serviceStatus!=2){
        return true;
      }else{
        return false;
      }
    },
    currentMessageList02(){
      var jsondata={};
      var converlist = this.currentMessageList.concat();
      for(let i=0;i<this.converMember.length;i++){
        jsondata[this.converMember[i].imAccount||this.converMember[i].userId]=this.converMember[i];
      }
      for(let j=0;j<converlist.length;j++){
        if(converlist[j].flow !== 'out'&&jsondata[converlist[j].from]){
          converlist[j].healthManagerTypeName=jsondata[converlist[j].from].healthManagerTypeName||'健康管理师';
        }else{
          converlist[j].healthManagerTypeName='健康管理师';
        }
      }
      return converlist;
    },
    currentMemJudge(){
      var cjudge=false;
      var arr01=[];
      var arr02=[];
      for(let i=0;i<this.converMember.length;i++){
        if(this.converMember[i].allowPrivateChat){
          arr02.push(this.converMember[i])
        }else{
          arr01.push(this.converMember[i])
        }
      }
      if(arr02.length>0&&arr01.length>0){
        cjudge=true
      }
      return cjudge;
    },
    name() {
      if (this.currentConversation.type === 'C2C') {
        return this.currentConversation.userProfile.nick || this.toAccount
      } else if (this.currentConversation.type === 'GROUP') {
        return this.currentConversation.groupProfile.name || this.toAccount
      } else if (this.currentConversation.conversationID === '@TIM#SYSTEM') {
        return '系统通知'
      }
      return this.toAccount
    },
    showMessageSendBox() {
      return this.currentConversation.type !== this.TIM.TYPES.CONV_SYSTEM
    },
    userArr(){
      var ujson = {}
      if (this.currentConversation.type === 'C2C') {
        ujson[this.currentConversation.userProfile.userID]={nick: this.currentConversation.userProfile.nick,avatar:this.currentConversation.userProfile.avatar}
        ujson[this.userID]={nick: this.currentUserProfile.nick,avatar:this.currentUserProfile.avatar}
      } else if (this.currentConversation.type === 'GROUP') {
        for(var i=0;i<this.currentMemberList.length;i++){
          ujson[this.currentMemberList[i].userID]=this.currentMemberList[i]
        }
      }
      return ujson
    },
    imageArr(){
      var imgarr = [];
      for(let i=0;i<this.currentMessageList02.length;i++){
        if(this.currentMessageList02[i].type === this.TIM.TYPES.MSG_IMAGE){
          try{
            imgarr.push(this.currentMessageList02[i].payload.imageInfoArray[1].imageUrl.split('?')[0])
          }catch(e){console.log(e)}
        }
      }
      return imgarr
    },
    dtitle(){
      try{
        var titlestr=this.name;
        if (this.currentConversation.type === 'GROUP') {
          var str = '('+this.converList02[this.currentConversation.conversationID].nowDay+'/'+this.converList02[this.currentConversation.conversationID].totalDay+'天)';
          titlestr+=str
        }
        document.title = titlestr;
        return titlestr;
      }catch(e){
      }
    }
  },
  watch: {
    '$route' (to, from) { //监听路由是否变化
      console.log("tototototototototoototot")
      //  console.log(from)
       if(from.path == '/im/atuser'){
      console.log("????????????????")
       }else if(to.path == '/im/chat'){
         console.log('xxxxxxxxxxxxxxxxxx')
           location.reload()
      }
    },
    isFocus:{
      handler: function(o,n){
        if(this.isIosOrAndroid()==2){
          this.$store.commit('upinputfocus',o)
        }
      },
      immediate: true
    },
    currentMessageList: {
      handler: function(o,n){
        this.fnGetTime(o)
        if(o.length < 10){
         // if( this.$route.query.status == 2){

        //  }else{
 this.fnGetmoreMessage()
        //  }
         
        }
      },
      immediate: true
    },
    currentUnreadCount(next) {
      if (!this.hidden && next > 0) {
        this.tim.setMessageRead({ conversationID: this.currentConversation.conversationID })
      }
    },
    hidden(next) {
      if (!next && this.currentUnreadCount > 0) {
        this.tim.setMessageRead({ conversationID: this.currentConversation.conversationID })
      }
    },
    toAccount(next){
      // this.isCompletedService = false
      // this.moreListJudge = false
      // if(this.currentConversation.type === 'C2C'){
      //   this.infoConll = false
      //   this.getInfoConll()
      //   this.fnGetC2cRelation()
      //   this.fnGetC2cServeDay()
      // }else{
      //   if(this.currentConversation.type === 'GROUP'){
      //     this.fnGetGroupRelation()
      //   }
      //   this.infoConll = false
      // }
    },
    selectedMember (newVal) {
      var self = this;
      if (newVal.length > 0 && this.listType === 'groupAt') {
        this.messageContent += newVal+' '
        this.$store.commit('uploadSelectedMember','')
        localStorage.removeItem('selectNickname')

        let u = navigator.userAgent, app = navigator.appVersion;
        let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        if(isIOS){
          self.$refs.msgInput.blur();
        }else{
          setTimeout(()=>{
              self.$nextTick(() => {
                self.$refs.msgInput.focus();
              })
            },500)
         }
      }
    }
  },
  created() {
    console.log(location.href)
    this.statusType = this.$route.query.status;
    this.init();
    // this.$bus.$on('image-preview', this.handlePreview)
  },
  activated(){
    if(this.$getCookie('gochat')){
      this.$removeCookie('gochat')
    }
    if(this.$route.query.conversationid!=this.currentConversation.conversationID){
      this.init();
    }else{
      this.tim.setMessageRead({ conversationID: this.currentConversation.conversationID })
    }
    this.scrollMessageListToButtom();
  },
  mounted(){
    var self = this;
    if (this.isIosOrAndroid()==1) {
      //获取原窗口的高度
      var originalHeight = document.documentElement.clientHeight || document.body.clientHeight;
      window.onresize = function() {
        //键盘弹起与隐藏都会引起窗口的高度发生变化
        var resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
        if (resizeHeight - 0 < originalHeight - 0) {
          //当软键盘弹起，在此处操作
          self.$store.commit('upinputfocus',true)
        } else {
          //当软键盘收起，在此处操作
          self.$store.commit('upinputfocus',false)
        }
      };
    }
    //获取权限
    // this.fnJsSdkSign();
  },
  methods: {
    //ctc
    
    getHistoryListGroupFun(){
      var self = this;
      var conversationid = this.$route.query.conversationid;
      var xtGroup= conversationid.substring(5)
      var params = {
          campGroupId: xtGroup,
          maxCnt: 10000,
          currentUserAccount: self.$getCookie('userID'),
          userImAccount: self.userID,
        }

        apiGetmoreGroupMessage(params).then(res => {
          if(res.status == 200){
            console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
            console.log(res.data)
            self.fnSetServiceMsg(res.data)
            //if(self.mmorejudge){
              //初始页面滚动到底部
              self.scrollMessageListToButtom();
            // }
          } 
        })
    },
    getHistoryListCtCFun(){
      var self = this;

      var conversationid = this.$route.query.conversationid;
      var hmid= conversationid.substring(3)
 
        var params = {
            userImAccount: self.userID,
            hgrImAccount:hmid,
            maxCnt: 1000
          }
         apiGetmoreC2cMessage(params).then(res => {
            self.moreListJudge = false
            if(res.status == 200){
              self.fnSetServiceMsg(res.data)   
              console.log('ctc')
              self.scrollMessageListToButtom();
              }
          })
    },
    fninfocus(e){
      this.isFocus = true
      this.isMoreOpen=false
      if(!e||!e.srcElement){
        e=arguments[0]
      }
      let obj = e.srcElement||this.$refs.msgInput;
      console.log(obj)
      obj.focus();
      const len = obj.value.length;
      //光标定位要加上 setTimeOut，不然就会重新光标定位失败
      setTimeout(()=>{
          obj.selectionStart = obj.selectionEnd = len;
      },60)
      // scrolltopnum=this.$refs['message-list'].scrollTop();
    },
    fninblur(callback){
      this.isFocus = false
      try{
        if (this.isIosOrAndroid()==2) {
          setTimeout(function(){
            const scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0
            window.scrollTo(0, Math.max(scrollHeight - 1, 0))
            if(callback && typeof callback == 'function'){
              callback();
            }
          },200)
        }
      }catch(e){}
    },
    isIosOrAndroid() {
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      if (isAndroid) {
          return 1
      }
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      if (isiOS) {
          return 2
      }
      return 0
    },
    //微信配置
    fnJsSdkSign(){
      var self = this;
      apiJsSdkSign({
        url: encodeURIComponent(location.href.split('#')[0])
      }).then(res => {
        const response = res.data
        console.log('--server--',response)
        wx.config({
          debug: false,
          appId: response.wx_app_id,
          timestamp: response.timestamp,
          nonceStr: response.nonce_str,
          signature: response.signature,
          jsApiList: [
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'onMenuShareQZone',
            'startRecord',
            'stopRecord',
            'onVoiceRecordEnd',
            'playVoice',
            'pauseVoice',
            'stopVoice',
            'onVoicePlayEnd',
            'uploadVoice',
            'downloadVoice',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'translateVoice',
            'getNetworkType',
            'openLocation',
            'getLocation',
            'hideOptionMenu',
            'showOptionMenu',
            'hideMenuItems',
            'showMenuItems',
            'hideAllNonBaseMenuItem',
            'showAllNonBaseMenuItem',
            'closeWindow',
            'scanQRCode',
            'chooseWXPay',
            'openProductSpecificView',
            'addCard',
            'chooseCard',
            'openCard',
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'getLocalImgData'
          ]
        })
        wx.error(res => {
          console.error(res)
          console.log('WxConfig验证失败')
        })
        wx.ready(() => {
          // wx.startRecord({})
          // setTimeout(function(){
          //   wx.stopRecord({})
          // },500)
        })
      })
    },
    fnaiteItem(name){
      if(this.prestatus){
        this.isMoreOpen=false
        this.messageContent += '@'+name+' '
        this.isRecord=false
        this.$nextTick(() => {
          this.$refs.msgInput.focus();
        })
      }
    },
    init(){
      var self = this;
      if(!self.isSDKReady){
        setTimeout(function(){
          self.init()
        },500)
      }else{
        // 是否有引用
        if(this.$route.query.quote){
           this.quoteFlag = true;
           this.hmname = this.$route.query.hmname || '';
           this.quotetxt = this.$route.query.quotetxt || '';
           if(!this.hmname){
             this.messageContent = ''
           }else if(this.quotetxt){
             this.messageContent = '@'+ this.$route.query.hmname+' ' || '';
           }else{
             this.messageContent = ''
           }
          
           
            let u = navigator.userAgent, app = navigator.appVersion;
            let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
            
            if(isIOS){
               setTimeout(()=>{
                  self.$nextTick(() => {
                    self.$refs.msgInput.blur();
                  })
                },500)
             
            }else{
              setTimeout(()=>{
                  self.$nextTick(() => {
                    self.$refs.msgInput.focus();
                  })
                },500)
            }
          
        }
        if(this.$route.query.conversationid){
          var conversationid = this.$route.query.conversationid;
          if(conversationid.indexOf('C2Chm_')<0&&conversationid.indexOf('GROUP')<0){
            conversationid='C2Chm_'+conversationid;
          }
          this.isCompletedService=false
          // //TODO修改

          // if(this.$route.query.status == 1 || this.$route.query.quote){
          if(this.$route.query.status !=2 ||this.$route.query.status != 3 || this.$route.query.quote){
            this.$store.dispatch(
              'checkoutConversation',
              conversationid
            )
            this.$store.commit('removeAtmeMesssage',conversationid)
          }
         
        }else{
          this.$store.commit('removeAtmeMesssage',this.currentConversation.conversationID)
        }
        if(this.currentMessageList.length<10){
          this.mmorejudge=true;
        }else{
          this.scrollMessageListToButtom();
          this.mmorejudge=false
        }
      
        if(reqCount == 0){
          var strid = this.$route.query.conversationid;;
          if(strid.indexOf('GROUP') >-1){
            this.getHistoryListGroupFun();
          }else{
            //  this.getHistoryListCtCFun();   // 暂时注解掉，，，，获取历史记录
          }
           reqCount++;
        }
      }
      
    },
    quoteCloseFn(){
      this.quoteFlag = false;
      this.quotetxt = ''
    },
    //切换私聊
    fnchangeConver(account){
      // this.$router.push({
      //   path: '/im/chat',
      //   query: {
      //     conversationid: 'C2C'+account
      //   }
      // })
      this.$store.dispatch(
        'checkoutConversation',
        'C2C'+account
      )
    },
    //进去团队介绍页
    fngoMempage(){
      this.$router.push({
        path: '/im/groupmem',
          query: {
          conversationid: this.currentConversation.conversationID
        }
      })
    },
    //监听聊天内容滚动
    onScroll() {
      let messageListNode = this.$refs['message-list']
      if (!messageListNode) {
        return
      }
      if (this.isCompleted&&this.isCompletedService) {
        return 
      }
      if(messageListNode.scrollTop<5){
        this.fnGetmoreMessage();
      }
    },
    // 直接滚到底部
    scrollMessageListToButtom() {
      var self = this;
      setTimeout(function(){
        self.$nextTick(() => {
            let messageListNode = self.$refs['message-list']
            if (!messageListNode) {
              return
            }
            messageListNode.scrollTop = messageListNode.scrollHeight
        })
      },500)
    },
    //获取更多对话-7天后对话从服务端拉取
    fnGetmoreMessage() {
      var self = this
      if(self.isCompletedService && self.isCompleted){
        return ;
      }
      if(!self.isCompleted){
        self.$store.dispatch('getMessageList', self.currentConversation.conversationID)
      }else{
        if(self.moreListJudge){
          return ;
        }
        self.moreListJudge = true
        if(self.currentConversation.type === 'C2C'){
          var params = {
            userImAccount: self.userID,
            hgrImAccount: self.toAccount,
            maxCnt: 15
          }
          if(self.currentMessageList.length==0){
          }else{
            params.startTime = self.currentMessageList[0].time
            if(self.currentMessageList[0].sequence){
              params.lastMsgKey = self.currentMessageList[0].sequence
            }
          }
          apiGetmoreC2cMessage(params).then(res => {
            self.moreListJudge = false
            if(res.status == 200){
              self.fnSetServiceMsg(res.data)
              if(self.mmorejudge){
                //初始页面滚动到底部
                self.scrollMessageListToButtom();
              }
            }else{
              self.$toast(res.msg);
              self.isCompletedService = true
            }
          })
        }else if(self.currentConversation.type === 'GROUP'){
          var params = {
            campGroupId: self.toAccount,
            maxCnt: 15
          }
          if(self.currentMessageList.length==0){
          }else{
            if(self.currentMessageList[0].sequence){
              params.msgSeq = self.currentMessageList[0].sequence
            }
          }
          apiGetmoreGroupMessage(params).then(res => {
            self.moreListJudge = false
            console.log("eeeeeeeeeeeeeeeeee")
            if(res.status == 200){
              self.fnSetServiceMsg(res.data)
              if(self.mmorejudge){
                //初始页面滚动到底部
                self.scrollMessageListToButtom();
              }
            }else{
              self.$toast(res.msg);
              self.isCompletedService = true
            }
          })
        }else{
          self.isCompletedService = true
        }
        
      }
    },
    fnSetServiceMsg(list) {
      var self = this
      if(!this.userArr){
        setTimeout(function(){
          self.fnSetServiceMsg(list)
        },200)
      }else{
        try{
          if(!list){
            list = []
          }
          list.sort(function(a,b){
            return a.time-b.time;
          })

       
          if(list.length>0){
            var arrdata = []
            for(var i=0;i<list.length;i++){
              if(this.currentConversation.conversationID){
              //  alert(this.currentConversation.type)  //GROUP
                 list[i].conversationID = this.currentConversation.conversationID
                 list[i].conversationType = this.currentConversation.type
                 list[i].isRead = true
                 list[i].nick = this.userArr[list[i].from].nick
                 list[i].avatar = this.userArr[list[i].from].avatar
              }else{

                var conversationid = this.$route.query.conversationid;
                var type = 'C2C'
                if(conversationid.indexOf('GROUP') > -1){
                    type = 'GROUP'
                }
 
                list[i].conversationID =  ''
                list[i].conversationType =  type
                list[i].isRead = true
                list[i].nick =  ''
                list[i].avatar =  ''
              }

              let val = self.$route.query.conversationid;
              if(val.indexOf('GROUP') > -1){
                 list[i].flow = self.userID==list[i].from?'out':'in';
              }
             

              if(self.currentConversation.type === 'GROUP'){
                list[i].flow = self.userID==list[i].from?'out':'in'
              }else if(self.currentConversation.type === 'C2C'){
               
              }

              arrdata.push(list[i])
            }
            //  self.$store.commit('addSeviceMessageList',arrdata)
            self.getHmArr(arrdata);
           
          }else{
            self.isCompletedService = true
          }
        }catch(e){
          setTimeout(function(){
            self.fnSetServiceMsg(list)
          },200)
        }
      }
    },
    async getHmArr(arrdata){
          console.log('============================')
            console.log(arrdata)
      var self = this;
      var tempArr = [];
      if(arrdata.length){
        for(var j = 0; j < arrdata.length; j++){
          var hmFlag = arrdata[j].from;
          if(hmFlag.indexOf('hm_') > -1){
             await self.getHmInfo(arrdata,arrdata[j], hmFlag, j);
          }
        }

        console.log('sssssssssssssssssssssss')
        console.log(self.convListArr)
 
        self.$store.commit('addSeviceMessageList',self.convListArr)
       }
       // self.$store.commit('addSeviceMessageList',arrdata)
    },
    getHmInfo(orgArr,arrdata, hmFlag, j){
      var self = this;
      self.convListArr = orgArr;
      apiGetHmInfo({
        middleId: hmFlag.split('_')[1]
      }).then(res => {
        if(res.status == 200){
          self.convListArr[j].nick =  res.data.nickname
          self.convListArr[j].avatar =  res.data.faceUrl
          // self.$set(list[i-1],'nick', res.data.nickname)
          // self.$set(list[i-1],'avatar', res.data.faceUrl)
        
        } 
      })
    },

    //获取服务器时间
    fnGetTime(next) {
      var topTimeList=[];
      for(var i=0;i<next.length;i++){
        topTimeList[i]={};
        try{
          if(next[i].time){
            if(i==0){
              topTimeList[0].time = next[0].time
            }else{
              if(next[i-1].time&&(next[i].time-next[i-1].time)>60){
                topTimeList[i].time = next[i].time
              }else{
                topTimeList[i].time=0
              }
            }
          }
        }catch(e){}
      }
      this.topTimeList = topTimeList
    },
    chooseRecord() {
      this.isRecord = !this.isRecord
      this.isMoreOpen = false
    },
    // 处理更多选项卡
    handleMore() {
      this.isRecord = false
      if (this.isFocus) {
        this.isFocus = false
        this.isMoreOpen = true
      } else {
        this.isMoreOpen = !this.isMoreOpen
      }
    },
    // 选项卡关闭
    handleClose() {
      this.isFocus = false
      this.isMoreOpen = false
    },
    // 聊天输入
    inputChange(e) {
      let _value = this.messageContent // 非当前值
      let newLength = _value.length
      if (this.oldLength > newLength) {
        this.oldLength = newLength
        return
      }
      this.oldLength = _value.length
      if (this.currentConversation.type === this.TIM.TYPES.CONV_GROUP && _value.substring(_value.length - 1, _value.length) == '@'){
        this.listType = 'groupAt'
        this.handleClose()
        this.isRecord = false
        this.fninblur();
        this.$router.push({
          path: '/im/atuser',
          query: {
            // conversationid: this.conversation.conversationID
          }
        })
      }
      if (_value.substring(_value.length - 1, _value.length) === ' ' && this.messageContent.indexOf('@ ') !== -1) {
        this.listType = ''
      }
    },
    // 发送text message
    sendMessage () {
      if (
        this.messageContent === '' ||
        this.messageContent.trim().length === 0
      ) {
        this.messageContent = ''
        this.oldLength = 0
        this.$store.commit('showMessage', {
          message: '不能发送空消息哦！',
          type: 'info'
        })
        return
      }
      let list = this.converMember.concat();
      let str = this.messageContent;
      let strlist = []
  
      for (let index = list.length-1; index >= 0 ; index--) {
        let str1 = '@'+list[index].nickname
        if(str.indexOf(str1) <0){
          list.splice(index,1);
        } else {
          let obj = {
            identity: list[index].healthManagerId,
            nickname: list[index].nickname
          }
          strlist.push(obj)
        }
        
      }
    
      if(list.length>0){ 
        var data = {
          content: this.messageContent,
          info: strlist
        }
        this.notify(JSON.stringify(data))
        return;
      }
      var messagestr = this.messageContent
      // 发送引用类型消息
      if(this.quotetxt){
         var data = {
          content: messagestr,
          type:12,
          originalMessage: this.quotetxt,
          replyMessage: messagestr,
        }
        var  message = this.tim.createCustomMessage({
          to: this.toAccount,
          conversationType: this.currentConversationType,
          payload: {
            data: JSON.stringify(data),
            originalMessage: this.quotetxt,
            extension: messagestr
          }
        })
      }else{
        var message = this.tim.createTextMessage({
          to: this.toAccount,
          conversationType: this.currentConversationType,
          payload: { text: messagestr }
        })
      }


      this.$store.commit('pushCurrentMessageList', message)
      this.scrollMessageListToButtom()
      this.tim.sendMessage(message).catch(error => {
        this.$store.commit('showMessage', {
          type: 'error',
          message: error.message
        })
      })
      this.messageContent = ''
      this.oldLength = 0
      this.isFocus = false
      this.isMoreOpen = false
      this.quotetxt = ''
      this.quoteFlag = false
    },
    
    notify(data){
      var self = this;
      apithirdmjknotify({
        CallbackCommand: 'Group.CallbackAfterSendMsg',
        From_Account: self.userID,
        GroupId: self.toAccount,
        MsgBody: {
          MsgContent: data,
          MsgType: "TIMCustomElem"
        },
        MsgTime: new Date().getTime()
      }).then(res =>{

      if(self.quotetxt){
         var messagestr = this.messageContent
         var data = {
          content: messagestr,
          type:12,
          originalMessage: this.quotetxt,
          replyMessage: messagestr,
        }
        var  message = this.tim.createCustomMessage({
          to: this.toAccount,
          conversationType: this.currentConversationType,
          payload: {
            data: JSON.stringify(data),
            originalMessage: self.quotetxt,
            extension: messagestr
          }
        })
      }else{
        var  message = self.tim.createTextMessage({
            to: self.toAccount,
            conversationType: self.currentConversationType,
            payload: { text: self.messageContent }
        })
      }
      
      self.$store.commit('pushCurrentMessageList', message)
      self.scrollMessageListToButtom()
      self.tim.sendMessage(message).catch(error => {
        self.$store.commit('showMessage', {
          type: 'error',
          message: error.message
        })
      })
      self.messageContent = ''
      self.quotetxt = ''
      self.quoteFlag = false
      })
    },
    //打开相机，相册
    sendPhoto (name) {
      this.chooseImage(name)
    },
    chooseImage (name) {
      let self = this
      this.$wx.chooseImage({
        sourceType: [name],
        count: 9,
        success: function (req) {
          async function sendimg(){
            for(let z=0;z<req.localIds.length;z++){
              await self.fnnext(req.localIds[z].toString())
            }
            console.log('发送图片完成')
            self.scrollMessageListToButtom()
          }
          sendimg();
        }
      })
      this.handleClose()
    },
    fnnext(localIdtext){
      var self = this
      let message = {}
      return new Promise(function (resolve, reject) {
        self.$wx.getLocalImgData({
          localId: localIdtext,
          success: function (res) {
            const localData = res.localData;
            let imageBase64 = '';
            if (localData.indexOf('data:image') == 0) {
              //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
              imageBase64 = localData;
            } else {
              //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
              //此时一个正常的base64图片路径就完美生成赋值到img的src中了
              imageBase64 = 'data:image/jpeg;base64,' + localData.replace(/\n/g, '');
            }
            message = self.tim.createImageMessage({
              to: self.toAccount,
              conversationType: self.currentConversationType,
              payload: {
                file: self.fndataimgfile(imageBase64,'image.jpeg')
              },
              onProgress: percent => {
                // self.$set(message, 'progress', percent) // 手动给message 实例加个响应式属性: progress
              }
            })
            self.$store.commit('pushCurrentMessageList', message)
            self.tim.sendMessage(message).then(() => {
              resolve('1')
            }).catch((err) => {
              resolve('2')
              // self.$store.commit('showMessage', {
              //   message: err.message,
              //   type: 'error'
              // })
            })
          }
        }); 
      })
    },
    fndataimgfile(dataurl, filename){
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while(n--){
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type:mime});
    },
    // 长按录音，监听在页面最外层div，如果是放在button的话，手指上划离开button后获取距离变化有bug
    handleLongPress (e) {
      this.startPoint = e.touches[0]
      if (e.target.id === 'record') {
        this.title = '正在录音'
        this.isRecording = true
        this.startRecording()
        this.canSend = true
      }else{
        this.canSend = false
      }
    },
    // 开始录音
    startRecording () {
      starttime=new Date().getTime();
      wx.startRecord({
        success: function (res) {
          console.log(res)
          console.log('录制start成功')
        },
        fail:function(res){
          console.log(res)
          console.log('录制start错误')
        }
      })
      wx.onVoiceRecordEnd({
      // 录音时间超过一分钟没有停止的时候会执行 complete 回调
        complete: function (res) {
          var localId = res.localId;
        }
      });
      // recorderManager.start(recordOptions)
    },
    // 录音时的手势上划移动距离对应文案变化
    handleTouchMove (e) {
      if (this.isRecording) {
        if (this.startPoint.clientY - e.touches[e.touches.length - 1].clientY > 100) {
          this.title = '松开手指，取消发送'
          this.canSend = false
        } else if (this.startPoint.clientY - e.touches[e.touches.length - 1].clientY > 20) {
          this.title = '上划可取消'
          this.canSend = true
        } else {
          this.title = '正在录音'
          this.canSend = true
        }
      }
    },
    // 手指离开页面滑动
    handleTouchEnd () {
      var self = this;
      endtime=new Date().getTime();
      this.isRecording = false
      if (self.canSend) {
        if((endtime-starttime)<1000){
          self.$toast('录音时间太短')
          return ;
        }
      }else{
        return ;
      }
      console.log(starttime,endtime)
      wx.stopRecord({
        success: function (res) {
          console.log(res)
          if (self.canSend) {
            // const message = self.tim.createAudioMessage({
            //   to: self.toAccount,
            //   conversationType: self.currentConversationType,
            //   payload: {
            //     file: res
            //   }
            // })
            // self.$store.commit('pushCurrentMessageList', message)
            // self.tim.sendMessage(message).then(() => {
            //   self.scrollMessageListToButtom()
            // })
          }
        },
        fail:function(res){
          console.log(res)
          console.log('录制错误')
        },
        complete:function(res){
          console.log('调用结束')
        }
      })
      // recorderManager.stop()
    },
  },
  filters:{
    fildate: function(data){
      if(!data){
        return ''
      }
      return getFullDate(new Date(data*1000))
      // var dateTimeStamp = data * 1000;
      // var result = '';
      // var now = this.nowtime;
      // var diffValue = now - dateTimeStamp;
      // var yearC = diffValue / 31104000000;
      // var monthC = diffValue / 2592000000;
      // var weekC = diffValue / (7 * 86400000);
      // var dayC = diffValue / 86400000;
      // var hourC = diffValue / 3600000;
      // var minC = diffValue / 60000;
      // if (yearC >= 1) {
      //   // result = parseInt(yearC) + "年前";
      //   result = getFullDate(new Date(dateTimeStamp))
      // } else if (monthC >= 1) {
      //   result = getFullDate(new Date(dateTimeStamp))
      //   // result = parseInt(monthC) + "个月前";
      // } else if (weekC >= 1) {
      //   result = getFullDate(new Date(dateTimeStamp))
      //   // result = parseInt(weekC) + "周前";
      // } else if (dayC >= 1) {
      //   result = getFullDate(new Date(dateTimeStamp))
      //   // result = parseInt(dayC) + "天前";
      // } else if (hourC >= 1) {
      //   // result = getFullDate(new Date(dateTimeStamp))
      //   result = parseInt(hourC) + "小时前";
      // } else if (minC >= 1) {
      //   result = parseInt(minC) + "分钟前";
      // } else{
      //   result = "刚刚";
      // }
      // return result;
    }
  }
}
function keepLastIndex(obj) {
  if (window.getSelection) {//ie11 10 9 ff safari
    obj.focus(); //解决ff不获取焦点无法定位问题
    var range = window.getSelection();//创建range
    range.selectAllChildren(obj);//range 选择obj下所有子内容
    try{
      range.collapseToEnd();//光标移至最后
    }catch(e){
      obj.focus();
      //range.collapse(obj,1);
    }
  }
  else if (document.selection) {//ie10 9 8 7 6 5
    var range = document.selection.createRange();//创建选择对象
    //var range = document.body.createTextRange();
    range.moveToElementText(obj);//range定位到obj
    range.collapse(false);//光标移至最后
    range.select();
  }
}
</script>
<style lang="scss" scoped>
.index-con{
  padding: 0;
  height: 100%;
  overflow-y: auto;
  width: 100%;
  background: #F8F6F3;
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  .group-menber{
    background-image: linear-gradient(0deg, rgba(252,252,252,0.50) 14%, #F7F7F7 100%);
    background-color: white;
    height: 3.693333rem;
    width: 100%;
    padding-top: .253333rem;
    .top-text{
      height: .373333rem;
      width: 100%;
      padding: 0 .493333rem 0 .88rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: .266667rem;
      color: #9B9B9B;
      letter-spacing: 0;
      background: url('../assets/image/ic_tishi@2x.png') no-repeat .426667rem center;
      background-size: .293333rem .293333rem;
      img{
        width: auto;
        height: .266667rem;
      }
    }
    .mem-list{
      display: flex;
      align-items: center;
      height: 2.6rem;
      margin-top: .173333rem;
      padding: 0 .3rem;
      width: 100%;
      .center-line{
        margin: .08rem .3rem 0 .166667rem;
        height: 2.413333rem;
        width: .013333rem;
        background:  #D8D8D8;
      }
      .left-mem{
        flex: 1;
        // overflow-x: auto;
        // -webkit-overflow-scrolling: touch;
        // white-space: nowrap;
      }
      .right-mem,
      .left-mem{
        height: 2.6rem;
        padding-top: .2rem;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
        white-space: nowrap;
        ul{
          li{
            display: inline-block;
            width: 1.773333rem;
            text-align: center;
            padding-top: .08rem;
            p{
              font-size: .266667rem;
              width: 100%;
              line-height: .373333rem;
              color: #9B9B9B;
              letter-spacing: 0;
              margin-top: .133333rem;
              @include ellipsis();
            }
            h5{
              font-size: .266667rem;
              width: 100%;
              line-height: .373333rem;
              color: black;
              letter-spacing: 0;
              margin: .053333rem 0 .08rem;
              @include ellipsis();
            }
            .zan-div{
              width: .4rem;
              height: .4rem;
              margin: 0 auto;
              background: url('../assets/image/ic_aixin_weidianxuan@2x.png');
              background-size: 100% 100%;
              &.active{
                background: url('../assets/image/ic_aixin_yidianxuan@2x.png');
                background-size: 100% 100%;
              }
            }
          }
        }
      }
    }
  }
  .chat-con{
    flex: 1;
    // background: url('../assets/image/chat-bot-bj.png') no-repeat left bottom .2rem;
    background-size: auto 2.853333rem;
    padding: .4rem;
    overflow-y: auto;
    .no-more{
      font-size: .266667rem;
      color: #9B9B9B;
      letter-spacing: 0;
      margin: 0 0 .4rem 0;
      line-height: .373333rem;
      text-align: center;
      width: 100%;
    }
    .top-time{
      font-size: .266667rem;
      color: #9B9B9B;
      letter-spacing: 0;
      margin: 0 .106667rem;
      line-height: .373333rem;
      text-align: center;
      width: 100%;
    }
  }
  .send-box{
    background: rgba(248, 246, 243, 1);
    min-height: 1.6rem;
    width: 100%;
    .bottom-div{
      height: 1.066667rem;
      width: 100%;
      margin: .266667rem 0;
      padding: 0 1.466667rem 0 .4rem;
      position: relative;
      .input-div{
        width: 100%;
        height: 1.066667rem;
        input{
          width: 100%;
          height: 1.066667rem;
          display: block;
          background: #F7F7F7;
          border: 1px solid #D8D8D8;
          border-radius: .133333rem;
          border-radius: .133333rem;
          font-size: .373333rem;
          color: #292929;
          display: flex;
          align-items: center;
          padding: 0 .426667rem;
          user-select: text!important;
          -webkit-user-select: text!important;
        }
      }
      .record{
        width: 100%;
        height: 1.066667rem;
        display: block;
        background: #F7F7F7;
        border: 1px solid #D8D8D8;
        border-radius: .133333rem;
        border-radius: .133333rem;
        font-size: .373333rem;
        color: #292929;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 .426667rem;
      }
      .btn-right,
      .btn-left{
        position: absolute;
        left: .4rem;
        top: .133333rem;
        width: .8rem;
        height: .8rem;
        img{
          width: 100%;
          height: 100%;
          display: block;
        }
      }
      .btn-right{
        left: auto;
        right: .4rem;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: .373333rem;
        color: $acolor;
      }
      &.not-send{
        .not-send-text{
          width: 100%;
          height: 44px;
          display: block;
          background: #F7F7F7;
          border: 2px solid #343434;
          border-radius: 22px;
          font-size: .373333rem;
          color: #C5C5C5;
          display: flex;
          align-items: center;
          padding: 0 .426667rem;
        }
        .btn-right,
        .btn-left{
          opacity: 0.4;
        }
      }
    }
    .quote-txt{
      color: #333;
      margin: 0 1.5rem .5rem .5rem;
      background: #D8D8D8;
      padding: .2rem 1rem 0.1rem .2rem;
      border-radius: 0.1rem;
      position: relative;

      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;


      .quote-close{
        position: absolute;
        top: 0.25rem;
        right: .3rem;
        width: .3rem;
        cursor: pointer;
      }
    }
    .bottom-image{
      background: #F7F7F7;
      width: 100%;
      height: 3.16rem;
      padding-top: .56rem;
      overflow: hidden;
      padding-right: .32rem;
      .block{
        float: left;
        width: 1.333333rem;
        margin: 0 .106667rem .2rem .426667rem;
        img{
          width: 100%;
          height: 1.333333rem;
          display: block;
        }
        p{
          width: 100%;
          text-align: center;
          margin-top: .133333rem;
          line-height: .36rem;
          font-size: .266667rem;
          color: #222222;
        }
      }
    }
  }
}
.record-modal{
  height: 3.613333rem;
  width: 6rem;
  background-color: black;
  opacity: 0.8;
  position: fixed;
  top: 4.8rem;
  z-index: 9999;
  left: 2rem;
  border-radius: .213333rem;
  display: flex;
  flex-direction: column;
  .wrapper{
    display: flex;
    height: 2.4rem;
    box-sizing: border-box;
    padding: 1rem;
    .modal-loading{
      opacity: 1;
      width: .48rem;
      height: .192rem;
      border-radius: .048rem;
      background-color: $acolor;
      animation: loading 2s cubic-bezier(.17,.37,.43,.67) infinite;
    }  
  } 
  .modal-title{
    text-align: center;
    color: white;
  } 
  &.modal-display{
    display: none;
  }
} 
@keyframes loading{
  0%{
    transform: translate(0,0);
  }
  50%{
    transform: translate(3rem,0);
    background-color: #f5634a;
    width: .964rem;
  } 
  100%{
    transform: translate(0,0);
  } 
}
@-webkit-keyframes loading{
  0%{
    transform: translate(0,0);
  }
  50%{
    transform: translate(3rem,0);
    background-color: #f5634a;
    width: .964rem;
  } 
  100%{
    transform: translate(0,0);
  } 
}
</style>